﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text;

using CE.Global;
using CE.User;

public partial class car_insurance_sign_in : MyLanguageBasePage
{
    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.SignInTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.SignInKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.SignInDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");
        if (_strCXLive == "0")
        {
            if (Session[CE.Global.General.Guest] == null)
            {
                _redirectUrl = CE.Global.General.GetUrl("~/Default.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            //else if (Session[CE.Global.General.Guest].ToString() == "Provider")
            //{
            //    if (Session[CE.Global.General.UserId] == null)
            //    {
            //        Response.Redirect("~/Provider/ProviderSecureLogin.aspx");
            //    }
            //}
        }

        if (Session[General.UserId] != null)
        {
            if (Session[General.UserTypeId].ToString() != CE.Global.CEUserType.Provider.ToString())
            {
                _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
            else
            {
                _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/car-details.aspx", Page);
                Response.Redirect(_redirectUrl);
            }
        }

        if (Page.PreviousPage != null)
        {
            //ContentPlaceHolder _ph = (ContentPlaceHolder)Page.PreviousPage.Master.FindControl("cpBody");
            //TextBox _txtExEmail = (TextBox)_ph.FindControl("txtEmail");
            //TextBox _txtExAuthCode = (TextBox)_ph.FindControl("txtPassword");

            TextBox _txtExEmail = (TextBox)Page.PreviousPage.Master.FindControl("usrLoginStatus").FindControl("txtEmail");
            TextBox _txtExAuthCode = (TextBox)Page.PreviousPage.Master.FindControl("usrLoginStatus").FindControl("txtPassword");
            if (_txtExEmail != null && _txtExAuthCode != null)
            {
                txtExEmail.Text = Server.HtmlEncode(_txtExEmail.Text);
                txtExAuthCode.Text = Server.HtmlEncode(_txtExAuthCode.Text);

                _txtExEmail.Text = "";
                _txtExAuthCode.Text = "";
                AutoLogin(200);
            }
        }

        if (!IsPostBack)
        {
            Session["CIMSG"] = null;
            Session["UMMSG"] = null;
            if (Request.Params["type"] != null)
            {
                if (Request.Params["type"].ToString() == "view")
                {
                    lblUserLoginTitle.Text = Resources.CarInsurance.SignIn; //"Sign in";
                }
                else if (Request.Params["type"].ToString() == "return")
                {
                    lblUserLoginTitle.Text = "Returning Members Log In Area";
                }
            }
            else
            {
                lblUserLoginTitle.Text = Resources.CarInsurance.SignIn; //"Sign in";
            }



            lblExEmail.Text = Resources.CarInsurance.EmailAddress;
            lblExAuthCode.Text = Resources.CarInsurance.Password;

            //this.value=!this.value?'Email':this.value;
            txtExEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtExEmail.ClientID + "','" + rfvExEmail.ClientID + "','" + rfvExEmailValid.ClientID + "')");
            txtExAuthCode.Attributes.Add("onblur", "ShowValidationEffect('" + txtExAuthCode.ClientID + "','" + rfvExAuthCode.ClientID + "')");

        }
        else
        {
            TextBox _txtExEmail = (TextBox)Page.Master.FindControl("usrLoginStatus").FindControl("txtEmail");
            TextBox _txtExAuthCode = (TextBox)Page.Master.FindControl("usrLoginStatus").FindControl("txtPassword");
            if (_txtExEmail != null && _txtExAuthCode != null)
            {
                if (_txtExEmail.Text != string.Empty && _txtExAuthCode.Text != string.Empty)
                {
                    txtExEmail.Text = Server.HtmlEncode(_txtExEmail.Text);
                    txtExAuthCode.Text = Server.HtmlEncode(_txtExAuthCode.Text);

                    _txtExEmail.Text = "";
                    _txtExAuthCode.Text = "";
                    AutoLogin(200);
                }
            }
        }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Page.Validate("excustomer");
        if (Page.IsValid)
        {
            AutoLogin(200);
        }
    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            if (Session[General.UserId] == null)
            {
                this.Cache.Remove(sKey);
                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        return _retValue;
    }

    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = DateTime.Now;
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;

        if (_account.UserTypeId == Convert.ToInt32(CE.Global.CEUserType.Provider))
        {
            CE.Provider.ProviderCompanyLink _comlink = new CE.Provider.ProviderCompanyLink();
            CE.Provider.ProviderCompanyLinkDB _comlinkdb = new CE.Provider.ProviderCompanyLinkDB();
            _comlink = _comlinkdb.GetProviderCompanyId(_account.CEID);
            if (_comlink != null)
            {
                Session[CE.Global.General.ProviderCompanyId] = _comlink.ProviderCompanyId;
            }
        }

        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.FirstName) + " " + Server.HtmlDecode(_profile.SurName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = DateTime.Now;
        _loghis.EndTime = DateTime.Now;
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            //_loginfo.Info1 = Request.Browser.Tables;
            //_loginfo.Info2 = Request.Browser.Platform;
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    private void AutoLogin(int LoginType)
    {
        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account
        Account _account = _accountdb.GetUserAccount(txtExEmail.Text.ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));

        if (_account != null)
        {
            if (CheckUserLoginCached(_account.CEID.ToString()))
            {
                _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);

                if (Server.HtmlDecode(txtExAuthCode.Text) == _account.AuthCode)
                {
                    if (_account.Status == true)
                    {
                        if (_account.Info1 == "0")
                        {
                            //Reset Email Fail Message
                            _account.Info1 = "";
                            _account.Info2 = "";
                            _accountdb.Insert(_account);
                        }

                        _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                        //divExErrorMessage.Visible = false;
                        GetUserInformation(_account);
                        SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                        CE.Global.General.CreateUpdateUserLoginCached(Page);
                        _account = null;
                        if (LoginType == 100)
                        {
                            _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                            Response.Redirect(_redirectUrl);
                        }
                        else
                        {
                            if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                            {
                                if (Session[General.CarId] != null)
                                {
                                    //Response.Redirect("~/car-insurance/car-and-policy-details.aspx");
                                    _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                    Response.Redirect(_redirectUrl);
                                }
                                else
                                {
                                    if (Request.Params["type"] != null)
                                    {
                                        if (Request.Params["type"].ToString() == "view")
                                        {
                                            _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                            Response.Redirect(_redirectUrl);
                                        }
                                        else if (Request.Params["type"].ToString() == "return")
                                        {
                                            //Response.Redirect("car-and-policy-details.aspx");
                                            _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                            Response.Redirect(_redirectUrl);
                                        }
                                    }
                                    else
                                    {
                                        //Response.Redirect("~/car-insurance/car-and-policy-details.aspx");
                                        _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                        Response.Redirect(_redirectUrl);
                                    }
                                }
                            }
                            else
                            {
                                //Response.Redirect("~/User/EditProfile.aspx");
                                _redirectUrl = CE.Global.General.GetUrl("~/user/saved-quotes.aspx", Page);
                                Response.Redirect(_redirectUrl);
                            }
                        }
                    }
                    else
                    {
                        lblLoginMessage.Text = "Your email has been blocked!";
                    }
                }
                else
                {
                    //divExErrorMessage.Visible = true;
                    _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 0);
                    lblLoginMessage.Text = Resources.Menu.EmailPasswordIncorrect; //"Email address or password is incorrect.";
                }
            }
            else
            {
                //Response.Redirect("UserMessage.aspx?ErrorCode=1993");
                //Response.Redirect("~/user/usermessage.aspx?mt=UM&ec=1993");
                _redirectUrl = CE.Global.General.GetUrl("~/user/usermessage.aspx", Page);
                Session["UMMSG"] = "UM,1993";
                Response.Redirect(_redirectUrl);
            }
        }
        else
        {
            //divExErrorMessage.Visible = true;
            lblLoginMessage.Text = Resources.Menu.EmailPasswordIncorrect;
        }
    }
}

